#include "include/lrc_parser.h"
#include "napi/native_api.h"
#include <string>

static napi_value NAPI_Global_readFileLrc(napi_env env, napi_callback_info info) {
    // 参数数量和类型检查
    size_t argc = 1;
    napi_value args[1] = {nullptr};

    napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    if (status != napi_ok || argc != 1) {
        napi_throw_type_error(env, nullptr, "Expected one argument (file path)");
        return nullptr;
    }

    napi_valuetype valuetype0;
    status = napi_typeof(env, args[0], &valuetype0);
    if (status != napi_ok || valuetype0 != napi_string) {
        napi_throw_type_error(env, nullptr, "Wrong argument type. String expected.");
        return nullptr;
    }
    
    // 获取字符串长度
    size_t str_len;
    status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &str_len);
    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "Failed to get string length.");
        return nullptr;
    }
    
    std::vector<char> buffer(str_len + 1);
    size_t copied;
    status = napi_get_value_string_utf8(env, args[0], buffer.data(), str_len + 1, &copied);
    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "Failed to get string value.");
        return nullptr;
    }
    std::string file_path(buffer.data());
    
    std::string lyrics = LrcParser::getLyrics(file_path);
    
    napi_value result;
    status = napi_create_string_utf8(env, lyrics.c_str(), lyrics.length(), &result);
    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "Failed to create string value.");
        return nullptr;
    }
    return result;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"readFileLrc", nullptr, NAPI_Global_readFileLrc, nullptr, nullptr, nullptr, napi_default, nullptr}};
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module LrcParserModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "lrcparser",
    .nm_priv = ((void *)0),
    .reserved = {0},
};

extern "C" __attribute__((constructor)) void RegisterLrcParserModule(void) { napi_module_register(&LrcParserModule); }
